package com.misboot.document.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 时间工具类
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    private static final SimpleDateFormat sftYMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat sftYMD = new SimpleDateFormat("yyyy-MM-dd");

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        return dateFormat.format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
    
    public static String getFirstDayPreMonth() {
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	Calendar cal_1 = Calendar.getInstance();//获取当前日期
    	cal_1.add(Calendar.MONTH, -1);
    	cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
    	String firstDay = format.format(cal_1.getTime()) + " 00:00:00";
    	return firstDay;
    }
    
    public static String getEndDayPreMonth() {
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	Calendar cale = Calendar.getInstance();
    	cale.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天
    	String lastDay = format.format(cale.getTime()) + " 23:59:59";
    	return lastDay;
    }


    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - past);
        Date today = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String result = sdf.format(today);
        return result;
    }

    public static String formateDate_yMdHms(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    public static String formateDate_yMd(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    public static List<String> splitDateList(Date startDate, Date endDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<String> listDate = new ArrayList<>();
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            while (calendar.getTime().before(endDate) || calendar.getTime().equals(endDate)) {
                listDate.add(dateFormat.format(calendar.getTime()));
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            return listDate;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listDate;
    }
    // 将字符串转换成日期格式 年月日时分秒 yyyy-MM-dd HH:mm:ss
    public static Date getYYYYMMDDHHMMSS(String strDate) throws ParseException {
        Date date = sftYMDHMS.parse(strDate);
        return date;
    }

    // 将字符串转换成日期格式 年月日 yyyy-MM-dd
    public static Date getYYYYMMDD(String strDate) throws ParseException {
        Date date = sftYMD.parse(strDate);
        return date;
    }

    public static boolean compareBTDayDate(String start, String end) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date startD = format.parse(start);
            Date endD = format.parse(end);
            if (startD.compareTo(endD) >= 0) {
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoorStr(String start, String end)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date startD = format.parse(start);
            Date endD = format.parse(end);
            String poor = getDatePoor(endD, startD);
            return poor.split("天")[0]+"天";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "0天";
    }

    /**
     * 计算两个时间差
     */
    public static Integer getDatePoorDay(Date start, Date end)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String poor = getDatePoor(end, start);
            return Integer.valueOf(poor.split("天")[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**

     * 获取一个月最后一天

     * @param date

     * @return

     */

    public static String getLastDayOfMonth(String date)

    {
        int year = Integer.parseInt(date.substring(0, 4));

        int month = Integer.parseInt(date.substring(5, 7));

        Calendar cal = Calendar.getInstance();

        cal.set(Calendar.YEAR, year);

        cal.set(Calendar.MONTH, month - 1);

        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));

        return(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));

    }

    /**

     * 获取一个月第一天

     * @param date

     * @return

     */

    public static String getFirstDayOfMonth(String date)

    {
        int year = Integer.parseInt(date.substring(0, 4));

        int month = Integer.parseInt(date.substring(5, 7));

        Calendar cal = Calendar.getInstance();

        cal.set(Calendar.YEAR, year);

        cal.set(Calendar.MONTH, month - 1);

        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DATE));

        return(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));

    }

    //判断当前时间是否在[startTime, endTime]区间，注意三个参数的时间格式要一致,在时间段内返回true，不在返回false
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(begin) && date.before(end);
    }

    //获取当前季度
    public static String getQuarter(){
        Calendar calendar = Calendar.getInstance();
        int quarter = calendar.get(Calendar.MONTH)/3+ 1;
        return calendar.get(Calendar.YEAR)+"-"+quarter;
    }

    //查询近num月的月份列表
    public static List<String> lastNumMonth(int num) throws Exception{
        List<String> monList = new ArrayList<>();
        for(int i=num-1; i>=0; i--){
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)-i); //逐次往前推1个月
            monList.add(String.valueOf(calendar.get(Calendar.YEAR))+"-" + (calendar.get(Calendar.MONTH)+1 < 10 ? "0" + (calendar.get(Calendar.MONTH)+1) : (calendar.get(Calendar.MONTH)+1)));
        }
        return monList;
    }

    /**
     * 计算两个日期之间的日期
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getDays(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }

    /**
     * 比较两个时间的大小，time1大于等于time2 返回true，否则返回fasle
     * @param time1
     * @param time2
     * @return
     */
    public static boolean compareDates(String time1, String time2) {
        int result = time1.compareTo(time2); // 比较两个时间

        if(result > 0) {
            return false;
        } else{
            return true;
        }
    }

    /**
     * 获取两个时间的时间差(单位 分钟)
     *
     * @throws Exception
     */
    public static long getDatePoorMin(Date endDate, Date nowDate) {
        long timeOne = endDate.getTime();
        long timeTwo = nowDate.getTime();
        long minute = 0;
        minute = (timeOne - timeTwo) / (1000 * 60);// 转化minute;
        return minute;
    }

    /**
     * 计算两个字符串日期相差天数
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    public static long calculateDays(String startDateStr, String endDateStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(startDateStr, formatter);
        LocalDate endDate = LocalDate.parse(endDateStr, formatter);
        return ChronoUnit.DAYS.between(startDate, endDate);
    }

}
